package priv.hxm.clien;
import priv.mill.net.MessageContexts;
import priv.mill.net.MessageObj;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client {

	public static void main(String[] args) {
		// new Client().connet("127.0.0.1",9999);
	}

	public void connet(String ip, int port) {
		EventLoopGroup group = null;// 声明线程池
		try {
			Bootstrap b = new Bootstrap();// 客户端启动对象
			group = new NioEventLoopGroup();// 实例化线程池
			b.group(group).channel(NioSocketChannel.class)// 配置管道
					.option(ChannelOption.TCP_NODELAY, true)// 设置tcp连接方式
					.handler(getHandler());
			ChannelFuture sync = b.connect(ip, port).sync();// 连接服务器
			// 循环向服务器发送消息
			sendMessage(sync);
			sync.channel().closeFuture().sync();// 关闭资源

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();// 释放线程池
		}

	}

	/**
	 * 
	 * MessageContexts.flage ： 1、允许发送 2、发完一个包等待服务器的处理，服务器处理完成之后，再允许发送 TODO 发送消息
	 * 
	 * @param sync
	 */
	private void sendMessage(ChannelFuture sync) {
		while (true) {// 持久连接,不断的发送信息
			MessageObj peekMessage = MessageContexts.getInstance()
					.peekMessage();
			if (peekMessage != null && MessageContexts.flage) {
				sync.channel().writeAndFlush(peekMessage.getMessage());
				MessageContexts.flage = false;
			}
		}
	}

	/**
	 * 提供通信的编码器和解码器，以及通信的回调处理对象
	 * 
	 * @return
	 */
	private ChannelInitializer<SocketChannel> getHandler() {
		return new ChannelInitializer<SocketChannel>() {// 添加转码器和逻辑处理对象
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				NetUtils.addDe(ch);
				ch.pipeline().addLast(new MyClientHandler());
			}

		};
	}
}
